<template>
  <div class="hr-main-container" style="max-width: 1200px; margin: 40px auto; padding: 20px;">
    <!-- 页面标题 -->
    <h2>HR 管理中心</h2>

    <!-- Tab 切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <!-- ========== 岗位管理 Tab ========== -->
      <el-tab-pane label="岗位管理" name="jobs">
        <div style="margin-bottom: 20px;">
          <el-button type="primary" @click="showAddJobForm">发布新岗位</el-button>
        </div>

        <!-- 新增/编辑表单弹窗 -->
        <el-card v-if="jobFormVisible" shadow="hover" style="margin-bottom: 20px;">
          <h3>{{ editingJob ? '编辑岗位' : '发布岗位' }}</h3>
          <el-form :model="job" :rules="jobRules" ref="jobForm" label-width="100px" size="small">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="职位名称" prop="name">
                  <el-input v-model="job.name" placeholder="如：Java开发工程师"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="薪资(元)" prop="salary">
                  <el-input-number v-model="job.salary" :min="0" style="width: 100%;"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="工作地点" prop="location">
                  <el-input v-model="job.location"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="经验要求" prop="experience">
                  <el-input v-model="job.experience" placeholder="如：3-5年"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="学历要求" prop="education">
                  <el-select v-model="job.education" placeholder="请选择" style="width: 100%;">
                    <el-option label="不限" value="不限"></el-option>
                    <el-option label="大专" value="大专"></el-option>
                    <el-option label="本科" value="本科"></el-option>
                    <el-option label="硕士" value="硕士"></el-option>
                    <el-option label="博士" value="博士"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="公司ID" prop="companyId">
                  <el-input-number v-model="job.companyId" :min="1" style="width: 100%;"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="职位描述" prop="jobDescription">
              <el-input type="textarea" :rows="3" v-model="job.jobDescription"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitJob">{{ editingJob ? '更新' : '发布' }}</el-button>
              <el-button @click="cancelJobEdit">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 岗位列表表格 -->
        <el-table :data="jobs" border v-loading="loadingJobs" style="width: 100%;">
          <el-table-column prop="jobId" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="职位名称"></el-table-column>
          <el-table-column prop="salary" label="薪资(元)" width="100"></el-table-column>
          <el-table-column prop="location" label="地点" width="100"></el-table-column>
          <el-table-column prop="experience" label="经验" width="100"></el-table-column>
          <el-table-column prop="education" label="学历" width="100"></el-table-column>
          <el-table-column prop="jobDescription" label="描述" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="{row}">
              <el-button size="mini" @click="editJob(row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="deleteJob(row.jobId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table> 

        <!-- 分页组件 -->
        <el-pagination
          @current-change="loadJobs"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          style="margin-top: 20px;"
        ></el-pagination>
      </el-tab-pane>

      <!-- ========== 用户查询 Tab ========== -->
      <el-tab-pane label="用户查询" name="users">
        <div style="margin-bottom: 20px;">
          <el-button type="primary" @click="loadUsers">刷新用户列表</el-button>
          
        </div>
        
        <!-- 用户列表表格 -->
        <el-table :data="users" border v-loading="loadingUsers" style="width: 100%;">
          <el-table-column prop="userID" label="用户ID" width="80"></el-table-column>
          <el-table-column prop="name" label="姓名" width="120"></el-table-column>
          <el-table-column prop="age" label="年龄" width="80"></el-table-column>
          <el-table-column prop="identity" label="身份标识" width="150"></el-table-column>
          <el-table-column prop="phone" label="电话" width="120"></el-table-column>
          <el-table-column prop="email" label="邮箱" width="150"></el-table-column>
          <el-table-column prop="location" label="所在地" width="120"></el-table-column>
          <el-table-column prop="resume" label="简历" show-overflow-tooltip></el-table-column>
          <el-table-column prop="attachments" label="附件" show-overflow-tooltip></el-table-column>
          <el-table-column prop="account" label="账号" width="120"></el-table-column>
          <el-table-column prop="password" label="密码" width="120"></el-table-column>
          <el-table-column prop="desiredJobId" label="期望职位ID" width="120"></el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{row}">
              <el-button size="mini" type="primary" @click="startChat(row)">聊天</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- ========== 个人中心 Tab ========== -->
      <el-tab-pane label="个人中心" name="profile">
        <h3>个人信息</h3>
        <el-form :model="hr" :rules="hrRules" ref="hrForm" label-width="100px" size="small">
          <el-form-item label="用户名">
            <el-input v-model="hr.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="hr.name"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="hr.email" type="email"></el-input>
          </el-form-item>
          <el-form-item label="公司ID" prop="companyId">
            <el-input-number v-model="hr.companyId" :min="1" style="width: 100%;"></el-input-number>
          </el-form-item>
          <el-form-item label="岗位ID" prop="jobId">
            <el-input-number v-model="hr.jobId" :min="1" style="width: 100%;"></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateProfile">保存修改</el-button>
            <el-button @click="logout">退出登录</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <chat-float ref="chatFloat"/>
  </div>

</template>

<script>
import request from '@/utils/request';
import ChatFloat from '../ChatFloat.vue';
export default {
   components: { ChatFloat },
  data() {
    return {
      activeTab: 'jobs', // 默认显示岗位管理

      // 岗位相关
      jobs: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loadingJobs: false,
      jobFormVisible: false,
      editingJob: null,
      job: {
        jobId: null,
        name: '',
        salary: 0,
        location: '',
        experience: '',
        education: '',
        companyId: 1,
        jobDescription: ''
      },
      jobRules: {
        name: [{ required: true, message: '请输入职位名称', trigger: 'blur' }],
        salary: [{ required: true, message: '请输入薪资', trigger: 'blur' }],
        location: [{ required: true, message: '请输入工作地点', trigger: 'blur' }]
      },

      // HR 信息
      hr: {
        hrId: null,
        username: '',
        name: '',
        email: '',
        companyId: 1,
        jobId: 1
      },
      hrRules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]
      },
      
      // 用户查询相关
      users: [],
      loadingUsers: false
    };
  },

  created() {
    this.checkLoginStatus();
    this.loadUserInfo();
    this.loadJobs();  // 🔔 初始化聊天用户

    const userDataStr = localStorage.getItem('hr_user');
    console.log("这是hrmainpage的userDataStr" + userDataStr);
    if (userDataStr) {
      const userData = JSON.parse(userDataStr);
      const hrid=userData.hrId;
       console.log('用户ID:', hrid);  // 输出: 200003
    }





    if (userDataStr) {
      const userData = JSON.parse(userDataStr);
      this.chatUser = {
        id: userData.hrId,
        type: 'HR'
      };
    } else {
      this.$router.push('/hr_login');
    }
  },

  methods: {
    // 检查是否已登录
    checkLoginStatus() {
      const token = localStorage.getItem('hr_token');
      if (!token) {
        this.$message.error('请先登录');
        this.$router.push('/hr_login');
      }
    },

    // 加载用户信息
    loadUserInfo() {
      const userDataStr = localStorage.getItem('hr_user');
      console.log("这是hrmainpage的userDataStr" + userDataStr);
      if (userDataStr) {
        const userData = JSON.parse(userDataStr);
        this.hr = { ...userData };
      } else {
        this.$message.error('用户信息丢失，请重新登录');
        this.$router.push('/hr_login');
      }
    },

    // 加载岗位列表
    loadJobs(page = 1) {
      this.loadingJobs = true;
      request.get('/select_job_page', {
        params: {
          page,
          size: this.pageSize,
          hrId: this.hr.hrId
        }
      }).then(res => {
        if (res.data.code === 1) {
          this.jobs = res.data.data.records;
          this.total = res.data.data.total;
          this.currentPage = page;
         
        } else {
          this.$message.error('加载岗位失败');
        }
   }).catch(error => {  // ✅ 添加 error 参数
        this.$message.error('网络错误，请检查连接');
        console.error('请求失败:', error);
      }).finally(() => {
        this.loadingJobs = false;
      });
    },

    // 显示新增岗位表单
    showAddJobForm() {
      this.editingJob = null;
      this.job = {
        jobId: null,
        name: '',
        salary: 0,
        location: '',
        experience: '',
        education: '',
        companyId: this.hr.companyId,
        jobDescription: ''
      };
      this.jobFormVisible = true;
    },

    // 编辑岗位
    editJob(row) {
      this.editingJob = row;
      this.job = { ...row };
      this.jobFormVisible = true;
    },

    // 取消编辑
    cancelJobEdit() {
      this.jobFormVisible = false;
      this.editingJob = null;
    },

    // 提交岗位（新增或更新）
    // 提交岗位（新增或更新）
submitJob() {
  this.$refs.jobForm.validate(valid => {
    if (!valid) return;
    
    // 关键修改：确保 job 对象包含 hrId
    this.job.hrId = this.hr.hrId;
    
    const url = this.job.jobId ? '/update_job' : '/add_job';
    request.post(url, this.job).then(res => {
      /* eslint-disable */
      if (res.data.code === 1) {
        this.$message.success(this.job.jobId ? '更新成功' : '发布成功');
        this.jobFormVisible = false;
        this.loadJobs(this.currentPage);
      } 
      else {
        console.log(url);
        console.log(res.data.code);
        this.$message.error('操作失败');
      }
    }).catch(() => {
      this.$message.error('请求失败，请重试');
    });
  });
},

    // 删除岗位
    deleteJob(id) {
      this.$confirm('确定要删除该岗位吗？', '提示', {
        type: 'warning'
      }).then(() => {
        request.delete(`/delete_job?id=${id}`).then(res => {
          if (res.data.code === 1) {
            this.$message.success('删除成功');
            this.loadJobs(this.currentPage);
          } else {
            this.$message.error('删除失败');
          }
        }).catch(() => {
          this.$message.error('请求失败，请重试');
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 更新个人信息
    updateProfile() {
      this.$refs.hrForm.validate(valid => {
        if (!valid) return;
        console.log("这是hrmainpage的hr" + this.hr);
        request.post('/HR_updata', this.hr).then(res => {
          if (res.data.code === 1) {
            this.$message.success('更新成功');
            // 同步到本地存储
            localStorage.setItem('hr_user', JSON.stringify(this.hr));
          } else {
            this.$message.error('更新失败');
          }
        }).catch(() => {
          this.$message.error('请求失败，请重试');
        });
      });
    },

    // 退出登录
    logout() {
      this.$confirm('确定要退出登录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        localStorage.removeItem('hr_token');
        localStorage.removeItem('hr_user');
        this.$message.success('已退出');
        this.$router.push('/hr_login');
      });
    },
    
    // 加载用户列表
    loadUsers() {
      this.loadingUsers = true;
      // request.get('http://localhost:8080/user/list')
       request.get('/user/list')  // ✅ 修改为相对路径
        .then(res => {
          if (res.data.code === 1) {
            this.users = res.data.data;
          } else {
            this.$message.error('加载用户列表失败');
          }
        })
        .catch(() => {
          this.$message.error('网络错误，请检查连接');
        })
        .finally(() => {
          this.loadingUsers = false;
        });
    },
    
   
    // 例子：HRMainPage.vue / UserMainPage.vue 的 startChat
startChat(row) {
  this.$refs.chatFloat.open(row, 'HR')
},
    
    // 处理标签页切换
    handleTabClick(tab) {
      if (tab.name === 'users' && this.users.length === 0) {
        this.loadUsers();
      }
    }
  }
};
</script>

<style scoped>
.hr-main-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}
.el-table {
  font-size: 14px;
}
.el-form-item {
  margin-bottom: 18px;
}
</style>